--[[1. 设备状态指示灯及中控复位 ]]
gpio.mode(4,gpio.OUTPUT)  
gpio.write(4,1)  --未连接成功的话LED熄灭

gpio.mode(5,gpio.OUTPUT)  --中控复位  
gpio.write(5,1)  

--[[2. 设备基本参数设置 ]]
configwifissid = "Young";
configwifipwd="52801314";
MqttUserString = "admin";
MqttPwdString = "52801314A";
MqttIPString = "121.80.77.183";  --！！！！！！！！！！！！！！！！IP失效！！！！！！！！！！！！！！！！！！！！！！！！！！！！1
MqttPort = 1883;--MQTT服务器端口参数
clientid = wifi.sta.getmac()
SubscribeTopic = "sixruning" --订阅
PublishTopic = "Young" --发送消息对象

--[[3. 设备连接WIFI ]]
wifi.setmode(wifi.STATIONAP)
apcfg={}
apcfg.ssid=configwifissid
apcfg.pwd=configwifipwd
wifi.sta.config(apcfg)
wifi.sta.autoconnect(1)

mqttClient=nil--连接状态标识
mqttConnectedFlage = 0;
client = mqtt.Client(clientid, 120, MqttUserString,MqttPwdString)--连接服务

--[[4. 设备连接中，定时器0检测连接 ]]
tmr.alarm(0, 500, 1, function()
    client:connect(MqttIPString, MqttPort,ConnectSuccess,ConnectFailed)
    --print("connect......");
    gpio.write(4,1-gpio.read(4)) --LED 2S 翻转
end)

--[[5. 设备连接成功 ]]
function ConnectSuccess(client)
     tmr.stop(0);--连接成功关闭定时器
     client:subscribe(SubscribeTopic, 0, subscribeSuccess)
     print("ON")
     mqttClient = client;
     mqttConnectedFlage = 1;
end

--[[6. 设备连接失败 ]]
function ConnectFailed(client,reason)
   mqttConnectedFlage = 0;
   tmr.start(0)
 --  print("failed reason: " .. reason)
end

--[[7. 设备订阅服务成功 ]]
function subscribeSuccess(client)
  --  print("subscribe Success")    
end

--[[8. 设备接收客户端数据转发给串口 ]]
client:on("message", function(client, topic, message)
       if message == "2266" then     --中控复位
           gpio.write(5,0)             
       elseif message == "6666" then  
           gpio.write(5,1) 
        else 
          uart.write(0,message) --把接收到的数据通过串口在发送出去   
       end  
end)

--[[9. 设备串口收到数据后转发给客户端 ]]
tmr.alarm(1, 2000, 0, function()  
  uart.on("data", 0,function(revdata) 
  --如果连接成功
   if mqttClient ~= nil and mqttConnectedFlage == 1 then
        mqttClient:publish("Young",revdata, 0, 0,
        function(client) 
         end)
   end                    
  end, 0)       
end) 

--[[10.设备连接成功状态指示灯]]
tmr.alarm(2, 2000, 1, function()
    if mqttClient ~= nil and mqttConnectedFlage == 1 then
        gpio.write(4,1-gpio.read(4)) --LED 2S 翻转
    end      
end)
